package com.forlove.app.qselect.login.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.forlove.app.ForloveApplication;
import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.LocationUtils;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.MyTimeUtils;
import com.forlove.app.common.utils.NetworkUtils;
import com.forlove.app.common.utils.PermissionsChecker;
import com.forlove.app.common.widget.ScrollerNumberPicker;
import com.forlove.app.manager.DataManager;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.qselect.login.entity.GpsEntity;
import com.forlove.app.qselect.login.entity.LimitEntity;
import com.forlove.app.qselect.login.presenter.ChoiceAgePresenter;
import com.forlove.app.qselect.login.view.ChoiceAgeView;
import com.forlove.app.qselect.login.widget.SetGpsDialog;
import com.forlove.app.qselect.webview.UserPrivateProtocolActivity;
import com.forlove.app.qselect.webview.UserProtocolActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by yjl on 2017/12/6.
 */

@RuntimePermissions
public class ChoiceNewAgeActivity extends BaseActivity<ChoiceAgePresenter>
        implements View.OnClickListener, ChoiceAgeView {
    public static final int REQUEST_PERMISSION = 1;
    public static final int REQUEST_GPS = 2;
    public static final int RESULT_GPS_SUCCESS = 10000;//获取gps成功
    public static final int RESULT_CONTACTS_SUCCESS = 10001;//获取通讯录成功
    public static final int RESULT_GPS_FAIL = 2;  //获取gps失败
    @BindView(R.id.bt_next_step)
    FrameLayout bt_next_step;

    @BindView(R.id.birthday_picker)
    ScrollerNumberPicker birthday_picker;

    @BindView(R.id.tx_login)
    TextView tx_login;

    @BindView(R.id.textview_user_protocol)
    TextView textview_user_protocol;

    @BindView(R.id.textview_user_private_protocol)
    TextView textview_user_private_protocol;

    @BindView(R.id.load_gps)
    ContentLoadingProgressBar load_gps;

    private ArrayList<String> mYearsList = new ArrayList<>();  //年
    private int mChoiceAge;//年龄
    private String birhtday;//出生年份

    //声明AMapLocationClient类对象
    private AMapLocationClientOption locationOption = null;
    private AMapLocationClient locationClient = null;
    private HandlerThread locationThread;
    private Handler getLocationHandler;
    private Handler locationHandler;
    private boolean getGps = false; //获取gps成功
    private long deltTime = 0;
    private SetGpsDialog setGpsDialog;
    private String loadUrl;
    private int nowYear = MyTimeUtils.getYearsNum(System.currentTimeMillis());

    @Override
    public int getLayoutId() {
        return R.layout.activity_choice_age;
    }

    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void needLocationPermission() {
        //获取到gps权限
        LocationUtils.openGPS(this);
        getGPSLocation();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        ChoiceNewAgeActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void refuseLocationPermission() {
        //拒绝gps权限
        LogUtil.e("yjl", "拒绝了gps授权");
    }

    @OnNeverAskAgain({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void neverAskPermission() {
        //不再询问授权
        bt_next_step.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(ChoiceNewAgeActivity.this, getString(R.string.str_tip_authorize_gps), Toast.LENGTH_LONG).show();
            }
        });
    }


    @Override
    public void initView() {
        if (presenter == null) {
            presenter = new ChoiceAgePresenter(this);
        }
        textview_user_protocol.setOnClickListener(this);
        textview_user_private_protocol.setOnClickListener(this);
        tx_login.setOnClickListener(this);
        load_gps.setVisibility(View.VISIBLE);
        bt_next_step.setOnClickListener(this);
        initBirthPicker();
        requestLimit(null);
        if (locationHandler == null) {
            locationHandler = new Handler(getMainLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    //处理gps成功请求
                    if (msg.what == 20008) {
                        //获取gps成功
                        GpsEntity gpsEntity = (GpsEntity) msg.obj;
                        if (gpsEntity != null) {
                            LogUtil.e("yjl", "gps lng:" + gpsEntity.lng + "  lat:" + gpsEntity.lat);
                            load_gps.setVisibility(View.VISIBLE);
                            getGps = true;
                            requestLimit(gpsEntity);
                        }
                    } else if (msg.what == 20009) {
                        //开始加载gps
                        load_gps.setVisibility(View.VISIBLE);
                    } else if (msg.what == 12) {
                        // 转到手机设置界面，用户设置GPS
//                        Toast.makeText(ChoiceNewAgeActivity.this,
//                                "获取位置服务失败，请在设置中打开位置服务：" + msg.what, Toast.LENGTH_SHORT).show();
                        Toast.makeText(ChoiceNewAgeActivity.this,
                                "获取位置服务失败，请在设置中打开位置服务", Toast.LENGTH_SHORT).show();
                        load_gps.setVisibility(View.INVISIBLE);
                        showTipDialog();
                    } else {
//                        Toast.makeText(ChoiceNewAgeActivity.this,
//                                "暂时无法获取位置信息：" + msg.what, Toast.LENGTH_SHORT).show();
                        if (Build.VERSION.SDK_INT >= 23) {
                            Toast.makeText(ChoiceNewAgeActivity.this, "暂时无法获取位置信息", Toast.LENGTH_SHORT).show();
                        }
                        load_gps.setVisibility(View.INVISIBLE);
                    }
                }
            };
        }
    }

    private void showTipDialog() {
        if (setGpsDialog == null) {
            setGpsDialog = new SetGpsDialog(this);
            setGpsDialog.setAgreeListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, REQUEST_GPS); // 设置完成后返回到原来的界面
                }
            });
        }
        setGpsDialog.show();
    }

    private void requestLimit(GpsEntity gpsEntity) {
        Map param = new HashMap();
        if (gpsEntity != null) {
            param.put("lat", gpsEntity.lat);
            param.put("lng", gpsEntity.lng);
        }
        presenter.loadLimitData(param);
    }

    private void initBirthPicker() {

        for (int i = 0; i < 100; i++) {
            mYearsList.add(String.valueOf(nowYear - i));
        }
        birthday_picker.setData(mYearsList);
        birthday_picker.setDefault(20);
        birhtday = birthday_picker.getSelectedText();
        //保存默认值
        int choiceYear = Integer.valueOf(birhtday);
        mChoiceAge = (nowYear - choiceYear);
        birthday_picker.setRightText(mChoiceAge + "岁");
        birthday_picker.setOnSelectListener(new ScrollerNumberPicker.OnSelectListener() {
            @Override
            public void endSelect(int id, String text) {
                int Year = Integer.valueOf(text);
                mChoiceAge = (nowYear - Year);
                birthday_picker.setRightText(mChoiceAge + "岁");
                birhtday = text;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showNextButtonView();
                    }
                });
            }

            @Override
            public void selecting(int id, String text) {
                int Year = Integer.valueOf(text);
                mChoiceAge = (nowYear - Year);
                birthday_picker.setRightText(mChoiceAge + "岁");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showNextButtonView();
                    }
                });
            }
        });
    }

    private void showNextButtonView() {
        if (bt_next_step != null && mChoiceAge >= 8) {
            bt_next_step.setBackground(getResources().getDrawable(R.drawable.bt_nextstep_selector));
        } else if (bt_next_step != null) {
            bt_next_step.setBackground(getResources().getDrawable(R.drawable.bg_blue_nextstep_corner_sel));
        }
    }

    /**
     * 开始获取gps
     */
    private synchronized void getGPSLocation() {
        if (locationThread == null) {
            locationThread = new HandlerThread("getLocation");
            locationThread.start();
        }
        if (getLocationHandler == null) {
            getLocationHandler = new Handler(locationThread.getLooper());
        }
        getLocationHandler.post(runnable);

    }

    //请求gps操作
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //初始化client
            if (locationClient == null) {
                locationOption = LocationUtils.getDefaultOption();
                locationClient = new AMapLocationClient(getApplicationContext());
                //设置定位参数
                locationClient.setLocationOption(locationOption);
            }
            // 设置定位监听
            locationClient.setLocationListener(new AMapLocationListener() {
                @Override
                public void onLocationChanged(AMapLocation location) {
                    synchronized (this) {
                        if (location != null) {
                            if (location.getErrorCode() == 0) {
                                LogUtil.e("yjl", "location code:" + location.getErrorCode()
                                        + "   address:" + location.getAddress());
                                //获取成功
                                GpsEntity gpsEntity = new GpsEntity();
                                gpsEntity.lng = String.valueOf(location.getLongitude());
                                gpsEntity.lat = String.valueOf(location.getLatitude());
                                DataManager.saveLocaition(ChoiceNewAgeActivity.this, gpsEntity);
                                if (locationHandler != null) {
                                    Message message = new Message();
                                    message.what = 20008;
                                    message.obj = gpsEntity;
                                    locationHandler.sendMessage(message);
                                }
                            } else {
                                if (locationHandler != null) {
                                    locationHandler.sendEmptyMessage(location.getErrorCode());
                                }
                                LogUtil.e("yjl", "location code:" + location.getErrorCode()
                                        + "   getErrorInfo:" + location.getErrorInfo());
                            }
                        }
                    }

                }
            });


            locationClient.startLocation();
            if (locationHandler != null) {
                locationHandler.sendEmptyMessage(20009);
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.textview_user_protocol:
                startActivity(new Intent(this, UserProtocolActivity.class));
                break;
            case R.id.textview_user_private_protocol:
                startActivity(new Intent(this, UserPrivateProtocolActivity.class));
                break;
            case R.id.tx_login:
                //登录用户不限制运营限制
                startActivity(new Intent(ChoiceNewAgeActivity.this, LoginInputPhoneActivity.class));
                break;
            case R.id.bt_next_step:
                defaultNextStep();
                break;
        }
    }


    /**
     * 下一步按钮默认设置
     */
    private void defaultNextStep() {
        if (mChoiceAge < 8) {
            Toast.makeText(this, "您的年龄太小，不适合使用圈一圈哦!", Toast.LENGTH_SHORT).show();
            return;
        } else if (mChoiceAge >= 100) {
            Toast.makeText(this, "您的年龄太大，不适合使用圈一圈哦!", Toast.LENGTH_SHORT).show();
            return;
        }

//        if (!getGps) {
//            Toast.makeText(this, "正在获取位置信息,请稍后!", Toast.LENGTH_SHORT).show();
//            return;
//        }
        if (NetworkUtils.instance(this).isNetworkAvailable()) {
//            UserManager.saveUserAge(ChoiceNewAgeActivity.this, birhtday);
//            startActivity(new Intent(ChoiceNewAgeActivity.this, RegisterPhoneActivity.class));
            load_gps.setVisibility(View.VISIBLE);
            requestLimit(null);
        } else {
            Toast.makeText(this, "请检查网络!", Toast.LENGTH_SHORT).show();
        }

    }


    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - deltTime > 2000) {
            deltTime = System.currentTimeMillis();
            Toast.makeText(this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
            return;
        }
        ForloveApplication.getInstance().exit();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtil.e("yjl", "requestCode:" + requestCode + "   resultCode:" + resultCode);
        if (requestCode == REQUEST_PERMISSION) {
            if (resultCode == RESULT_GPS_SUCCESS && data != null) {
                GpsEntity gps = (GpsEntity) data.getSerializableExtra("gps");
                if (gps != null && locationHandler != null) {
                    DataManager.saveLocaition(ChoiceNewAgeActivity.this, gps);
                    Message message = new Message();
                    message.what = 20008;
                    message.obj = gps;
                    locationHandler.sendMessage(message);
                }
            }
        } else if (requestCode == REQUEST_GPS) {
            if (setGpsDialog != null) {
                setGpsDialog.dismiss();
            }
            getGPSLocation();
        }

    }

    @Override
    protected void onDestroy() {
        if (locationClient != null) {
            locationClient.stopLocation();
            locationClient.onDestroy();
        }
        if (locationThread != null) {
            locationThread.quit();
            locationThread = null;
        }
        if (locationHandler != null) {
            locationHandler.removeCallbacksAndMessages(null);
            locationHandler = null;
        }
        if (getLocationHandler != null) {
            getLocationHandler.removeCallbacksAndMessages(null);
            getLocationHandler = null;
        }
        super.onDestroy();
    }

    //不限制运营,可以注册
    private void canRegister() {
        bt_next_step.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mChoiceAge < 8) {
                    Toast.makeText(ChoiceNewAgeActivity.this, "您的年龄太小，不适合使用圈一圈哦!", Toast.LENGTH_SHORT).show();
                    return;
                } else if (mChoiceAge >= 100) {
                    Toast.makeText(ChoiceNewAgeActivity.this, "您的年龄太大，不适合使用圈一圈哦!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (NetworkUtils.instance(ChoiceNewAgeActivity.this).isNetworkAvailable()) {
                    UserManager.saveUserAge(ChoiceNewAgeActivity.this, birhtday);
                    startActivity(new Intent(ChoiceNewAgeActivity.this, RegisterPhoneActivity.class));
                } else {
                    Toast.makeText(ChoiceNewAgeActivity.this, "请检查网络!", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void limitRegister() {
        //限制运营
        if (PermissionsChecker.getLocationPermission(this)) {
            //如果已经获取到了gps权限，检查gps
            ChoiceNewAgeActivityPermissionsDispatcher.needLocationPermissionWithPermissionCheck(this);
            bt_next_step.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //跳转授权页
                    if (!getGps) {
                        Toast.makeText(ChoiceNewAgeActivity.this, "正在获取位置信息,请稍后!", Toast.LENGTH_SHORT).show();
                    }
                    ChoiceNewAgeActivityPermissionsDispatcher.
                            needLocationPermissionWithPermissionCheck(ChoiceNewAgeActivity.this);
                }
            });
        } else {
            //未授权
            gpsUnAvailable();
        }
    }

    private void gpsUnAvailable() {
        bt_next_step.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mChoiceAge < 8) {
                    Toast.makeText(ChoiceNewAgeActivity.this, "您的年龄太小，不适合使用圈一圈哦!", Toast.LENGTH_SHORT).show();
                    return;
                } else if (mChoiceAge >= 100) {
                    Toast.makeText(ChoiceNewAgeActivity.this, "您的年龄太大，不适合使用圈一圈哦!", Toast.LENGTH_SHORT).show();
                    return;
                }
                //跳转授权页
                UserManager.saveUserAge(ChoiceNewAgeActivity.this, birhtday);

                Intent intent = new Intent(ChoiceNewAgeActivity.this, PermissionCheckerActivity.class);
                intent.putExtra("loadUrl", loadUrl);
                startActivityForResult(intent, REQUEST_PERMISSION);
            }
        });
    }

    //不可以注册
    private void registerUnavailable() {
        //不能注册
        bt_next_step.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(ChoiceNewAgeActivity.this, LimitAreaActivity.class));
            }
        });

    }

    //限制登录
    private void loginUnavailable() {
        tx_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(ChoiceNewAgeActivity.this, "该地区暂时无法登录!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void showErrorData(NetworkManager.ResultCode resultCode, String msg) {
        super.showErrorData(resultCode, msg);
        load_gps.setVisibility(View.INVISIBLE);
    }

    @Override
    public void updateLimitView(LimitEntity limitEntity) {
        load_gps.setVisibility(View.INVISIBLE);
        if (limitEntity != null && !getGps) {
            //第一次判断是否开启运营限制
            if (limitEntity.restrict) {
                //运营限制
                loadUrl = limitEntity.url;
                limitRegister();
            } else {
                //未运营限制,直接跳转注册登录页
                canRegister();
            }
        } else if (getGps && limitEntity != null) {
            if (!limitEntity.canreg) {
                registerUnavailable();
            } else {
                canRegister();
            }
            if (!limitEntity.canlogin) {
                loginUnavailable();
            }
        }
    }


}
